#include "looplist.h"
#include <stdio.h>
#include <stdlib.h>
//创建循环链表
LoopList_t *createLoopList() {
    LoopList_t *table =NULL;
    table=malloc(sizeof(LoopList_t));
    if (table == NULL) {
        fprintf(stderr, "Error allocating memory for LoopList_t\n");
        return NULL;
    }
    table->head.next=table->tail=&table->head;
    table->count = 0;
    return table;
}

//释放循环链表
void releaseLoopList(LoopList_t *table) {
     if(table!=NULL&&table->head.next!=&table->head){
        node_t *p=&table->head;
        while(p->next!=&table->head){
            node_t *temp=p->next;
            p->next=temp->next;
            free(temp);
        }
        free(table);
     }
}

//头插
int insertLoopListHead(LoopList_t *table, Element_t value) {
    if (table == NULL) {
        printf( "Error: list is NULL\n");
        return -1;
    }
    node_t *new_node=malloc(sizeof(node_t));
    if (new_node == NULL) {
        fprintf(stderr, "Error allocating memory for new_node\n");
        return -1;
    }
    new_node->val = value;
    new_node->next = table->head.next;
    table->head.next = new_node;
    //如果是第一个节点插入，更新tail指针
    if(table->tail==&table->head) table->tail=new_node;
    ++table->count;

    return 0;
}

//尾插
int insertLoopListTail(LoopList_t *table, Element_t value) {
    if (table == NULL) {
        printf("Error: list is NULL\n");
        return -1;
    }
    node_t *new_node = malloc(sizeof(node_t));
    if (new_node == NULL) {
        fprintf(stderr, "Error allocating memory for new_node\n");
        return -1;
    }

    new_node->val = value;
    //将新节点指向头节点
    new_node->next = &table->head;
    //将原尾节点的next指向新节点
    table->tail->next = new_node;
    //更新尾节点指针
    table->tail = new_node;
    ++table->count;
    return 0;
}

//删除值为value的节点
int deleteLoopListValue(LoopList_t *table, Element_t value) {
    if (table == NULL) {
        printf("Error: list is NULL\n");
        return -1;
    }
    node_t *p=&table->head;
    while(p->next!=&table->head){
        if(p->next->val==value) break;
        p=p->next;
            return 0;
        }

    //没有找到要删除的节点
    if(p->next==&table->head){printf("value not found\n"); return -1;}

    node_t *temp=p->next;
    p->next=temp->next;
    //如果删除的是尾节点，更新tail指针
    if(table->tail==temp) table->tail=p;
    free(temp);
    --table->count;
    return 0;
}

void showLoopList(const LoopList_t *table) {
    if (table == NULL) {
        printf( "Error: table is NULL\n");
        return;
    }

    node_t *p =table->head.next;
    //node_t *p=&table->head.next; //在table前多打一个 &
    //如果写成这样，最多只能打印一出一个随机大的数和测试中的521，还记得为什么吗？
    printf("LoopList's size is %d\n", table->count);
    while (p != &table->head) {
        printf("%d\t", p->val);
        p = p->next;
    }
    printf("\n");


}
